#!/usr/bin/env python3
"""
文件内容分析工具
提供多种文本统计功能：字符统计、词汇统计、语句统计、代码分析
"""

import sys
import re
import os
from pathlib import Path


class FileAnalyzer:
    """文件分析器类"""
    
    def __init__(self, file_path):
        self.file_path = file_path
        self.text_data = self._load_file_content()
    
    def _load_file_content(self):
        """加载文件内容，支持多种编码格式"""
        file_location = Path(self.file_path)
        
        if not file_location.exists():
            print(f"错误：找不到文件 '{self.file_path}'")
            sys.exit(1)
            
        encoding_list = ['utf-8', 'gbk', 'gb2312', 'latin-1']
        
        for encoding_type in encoding_list:
            try:
                with open(self.file_path, 'r', encoding=encoding_type) as file_obj:
                    return file_obj.read()
            except UnicodeDecodeError:
                continue
        
        # 如果标准编码都失败，使用二进制读取并尝试解码
        try:
            with open(self.file_path, 'rb') as file_obj:
                binary_data = file_obj.read()
                return binary_data.decode('utf-8', errors='replace')
        except Exception as error:
            print(f"错误：无法读取文件 - {error}")
            sys.exit(1)
    
    def calculate_characters(self):
        """计算字符总数（包含所有空白字符）"""
        return len(self.text_data)
    
    def calculate_words(self):
        """计算词汇数量（使用空白字符分割）"""
        word_list = self.text_data.split()
        return len(word_list)
    
    def calculate_sentences(self):
        """计算语句数量（基于句子结束标点）"""
        # 使用句号、问号、感叹号作为句子分隔符
        sentence_endings = re.split(r'[.!?]+', self.text_data)
        # 过滤空字符串并统计
        valid_sentences = [s for s in sentence_endings if s.strip()]
        return len(valid_sentences)
    
    def analyze_code_structure(self):
        """
        分析代码文件结构
        返回：行数统计字典
        """
        lines = self.text_data.split('\n')
        line_count = len(lines)
        blank_line_count = 0
        comment_line_count = 0
        content_line_count = 0
        
        # 获取文件扩展名判断文件类型
        file_ext = Path(self.file_path).suffix.lower()
        # 支持的文件类型
        supported_code_files = {'.py', '.java', '.c', '.cpp', '.js', '.ts', '.html', '.css', '.php'}
        
        is_programming_file = file_ext in supported_code_files
        
        for line_content in lines:
            stripped_content = line_content.strip()
            
            # 统计空行
            if not stripped_content:
                blank_line_count += 1
                continue
            
            # 代码文件进行注释分析
            if is_programming_file:
                # Python风格单行注释
                if stripped_content.startswith('#'):
                    comment_line_count += 1
                # 处理行内注释
                elif '#' in stripped_content:
                    code_section = stripped_content.split('#')[0].strip()
                    if code_section:
                        content_line_count += 1
                        comment_line_count += 1
                    else:
                        comment_line_count += 1
                else:
                    content_line_count += 1
            else:
                # 非代码文件的所有非空行都视为内容行
                content_line_count += 1
        
        return {
            'total_lines': line_count,
            'blank_lines': blank_line_count,
            'comment_lines': comment_line_count,
            'content_lines': content_line_count
        }


def show_usage():
    """显示使用说明"""
    print("文件分析工具使用说明:")
    print("命令格式: python file_analyzer.py [选项] [文件名]")
    print("\n可用选项:")
    print("  -c  统计字符数量")
    print("  -w  统计词汇数量")
    print("  -s  统计语句数量")
    print("  -a  分析代码结构（行数统计）")
    print("\n示例:")
    print("  python file_analyzer.py -c example.txt")
    print("  python file_analyzer.py -a program.py")


def process_command():
    """处理命令行参数并执行相应操作"""
    if len(sys.argv) != 3:
        show_usage()
        sys.exit(1)
    
    option = sys.argv[1]
    input_file = sys.argv[2]
    
    # 验证文件是否存在
    if not os.path.isfile(input_file):
        print(f"错误：文件 '{input_file}' 不存在")
        sys.exit(1)
    
    analyzer = FileAnalyzer(input_file)
    
    if option == '-c':
        char_count = analyzer.calculate_characters()
        print(f"文件字符总数: {char_count}")
    
    elif option == '-w':
        word_count = analyzer.calculate_words()
        print(f"文件词汇总数: {word_count}")
    
    elif option == '-s':
        sentence_count = analyzer.calculate_sentences()
        print(f"文件语句总数: {sentence_count}")
    
    elif option == '-a':
        analysis_result = analyzer.analyze_code_structure()
        print("=== 文件结构分析 ===")
        print(f"总行数:     {analysis_result['total_lines']}")
        print(f"空白行:     {analysis_result['blank_lines']}")
        print(f"注释行:     {analysis_result['comment_lines']}")
        print(f"内容行:     {analysis_result['content_lines']}")
    
    else:
        print("错误：无效的选项参数")
        show_usage()
        sys.exit(1)


if __name__ == '__main__':
    process_command()